package com.cacho.s2b.lesson.learn;

import com.cacho.s2b.lesson.utils.Constants;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.x509.X509V3CertificateGenerator;

import java.math.BigInteger;
import java.security.KeyStore;
import java.security.Security;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.security.auth.x500.X500Principal;
import java.util.Date;
import java.io.FileOutputStream;

public class LearnJks {

    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());  //注册BC Provider，因为有些关于证书的操作使用到了BouncyCastle这个第三方库就顺便注册上了，其实不注册也行

        KeyStore keyStore = KeyStore.getInstance(Constants.JKS);
        keyStore.load(null, null);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(Constants.RSA);
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        X509Certificate certificate = generateCertificate(publicKey, privateKey);
        keyStore.setKeyEntry("alias", privateKey, "password".toCharArray(), new Certificate[]{certificate});

        FileOutputStream fileOutputStream = new FileOutputStream("keystore.jks");
        keyStore.store(fileOutputStream, "password".toCharArray());
        fileOutputStream.close();
    }
    /**
     * 生成根证书(被BC废弃，但可以使用)
     */
    private static X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey) throws Exception {
        X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
        certGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGenerator.setIssuerDN(new X500Principal("CN=Test Certificate&quot"));
        certGenerator.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24));
        certGenerator.setNotAfter(new Date(System.currentTimeMillis() + 1000L * 60 * 60 * 24 * 365));
        certGenerator.setSubjectDN(new X500Principal("CN=Test Certificate&quot"));//设置证书使用者
        certGenerator.setPublicKey(publicKey); //设置证书公钥
        certGenerator.setSignatureAlgorithm("SHA256WithRSA"); //设置签名算法

        return certGenerator.generate(privateKey);
    }
}
